 package com.miaoxun.service.impl;

import com.basemapper.BasicMapper;
import com.github.pagehelper.Page;
import com.miaoxun.common.util.Constant;
import com.miaoxun.dao.TaskMapper;
import com.miaoxun.domain.entity.Task;
import com.miaoxun.domain.model.DataModel;
import com.miaoxun.domain.param.BaseParam;
import com.miaoxun.domain.util.PageUtil;
import com.miaoxun.service.timer.quartz.job.ScheduleJob;

import com.miaoxun.service.timer.quartz.utils.QuartzManager;
import com.miaoxun.service.timer.quartz.utils.ScheduleJobUtils;
import com.miaoxun.service.util.TaskService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Service
public class TaskServiceImpl extends BaseServiceImpl<Task> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    QuartzManager quartzManager;


    @Override
    public void initSchedule()   {
        // 这里获取任务信息数据
        List<Task> jobList = getAll();
        for (Task scheduleJob : jobList) {
            if ("1".equals(scheduleJob.getJobStatus())) {
                ScheduleJob job = ScheduleJobUtils.entityToData(scheduleJob);
                quartzManager.addJob(job);
            }
        }
    }

    @Override
    public void changeStatus(Long jobId, String cmd) throws SchedulerException {
        Task scheduleJob = getModelById(jobId);
        if (scheduleJob == null) {
            return;
        }
        if (Constant.STATUS_RUNNING_STOP.equals(cmd)) {
            quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJob));
            scheduleJob.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
        } else {
            if (!Constant.STATUS_RUNNING_START.equals(cmd)) {
            } else {
                scheduleJob.setJobStatus(ScheduleJob.STATUS_RUNNING);
                quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJob));
            }
        }
        update(scheduleJob);
    }

    @Override
    public DataModel<List<Task>> GetTables(BaseParam p) {
        Page page = PageUtil.startPage(p.getOffset(), p.getLimit(), p.getOrder(), p.getSort());
        List<Task> l = getAll();
        DataModel<List<Task>> dataModel = new DataModel<>();
        dataModel.setCount(page.getTotal());
        dataModel.setList(l);
        return dataModel;
    }



    @Override
    protected BasicMapper getMapper() {
        return taskMapper;
    }
}